package com.itjiange.service;

import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import com.itjiange.utils.ProfileUtils;

import java.util.concurrent.TimeUnit;

import static com.itjiange.constant.LoggerConstant.logger;

/**
 * 监听启动
 *
 * @author ItJiange
 * @date 2023/10/20
 */
public class FileMonitorService {
    private FileAlterationMonitor monitor;
    public FileMonitorService() {
        // 文件目录
        String rootDir = ProfileUtils.getContext();
        // 间隔时间2秒
        long intervalTime = TimeUnit.SECONDS.toMillis(2);
        FileAlterationObserver observer = new FileAlterationObserver(rootDir);
        // 添加文件监听
        observer.addListener(new FileListenerService());
        // 创建文件监听者
        monitor = new FileAlterationMonitor(intervalTime, observer);
    }

    public void stopFileMonitor() {
        try {
            monitor.stop();
            logger.info("文件监听停止");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void startFileMonitor() {
        // 启动监听
        try {
            monitor.start();
            logger.info("文件监听启动");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
